<?php

namespace App\Http\Controllers\API;

use App\Http\Controllers\Controller;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Validation\ValidationException;

class AuthController extends Controller
{
    /**
     * 处理用户登录并生成令牌
     */
    public function login(Request $request)
    {
        $request->validate([
            'email' => 'required|email',
            'password' => 'required',
            'device_name' => 'nullable|string',
        ]);

        $user = User::where('email', $request->email)->first();

        if (! $user || ! Hash::check($request->password, $user->password)) {
            throw ValidationException::withMessages([
                'email' => ['提供的凭据不正确。'],
            ]);
        }

        // 使用设备名称或默认名称
        $deviceName = $request->device_name ?? $request->userAgent() ?? 'unknown';
        
        // 删除用户以前的所有令牌
        // $user->tokens()->delete(); // 取消注释此行如果你想要单会话登录

        // 创建新令牌
        $token = $user->createToken($deviceName)->plainTextToken;

        return response()->json([
            'user' => $user,
            'token' => $token,
        ]);
    }

    /**
     * 用户注册并生成令牌
     */
    public function register(Request $request)
    {
        $request->validate([
            'name' => 'required|string|max:255',
            'email' => 'required|string|email|max:255|unique:users',
            'password' => 'required|string|min:8|confirmed',
            'device_name' => 'nullable|string',
        ]);

        $user = User::create([
            'name' => $request->name,
            'email' => $request->email,
            'password' => Hash::make($request->password),
        ]);

        $deviceName = $request->device_name ?? $request->userAgent() ?? 'unknown';
        $token = $user->createToken($deviceName)->plainTextToken;

        return response()->json([
            'user' => $user,
            'token' => $token,
        ], 201);
    }

    /**
     * 用户登出（撤销当前令牌）
     */
    public function logout(Request $request)
    {
        // 撤销当前令牌
        $request->user()->currentAccessToken()->delete();

        return response()->json(['message' => '成功登出']);
    }

    /**
     * 获取当前用户信息
     */
    public function user(Request $request)
    {
        return response()->json($request->user());
    }
}
